package com.onefish.toolkit.natives.support;

import com.sun.jna.Library;
import com.sun.jna.Native;

import java.util.concurrent.ConcurrentHashMap;

public class LibraryPool {
    private static final ConcurrentHashMap<LibraryKey, Library> LIBS_POOL = new ConcurrentHashMap<>();

    /**
     * 加载或获取已缓存的 JNA 接口实例
     *
     * @param libPath        动态库路径（如 "/one-fish/linux-x64/libbiz.so"）
     * @param interfaceClass JNA 接口类（需继承 Library）
     * @return 已加载的接口实例
     */
    @SuppressWarnings("unchecked")
    public static <T extends Library> T load(String libPath, Class<T> interfaceClass) {
        LibraryKey key = new LibraryKey(libPath, interfaceClass);
        return (T) LIBS_POOL.computeIfAbsent(key, k ->
                Native.load(libPath, interfaceClass)
        );
    }

}
